package com.hlf.common.utils;

import com.hlf.common.constants.Constants;
import com.hlf.common.exception.BusinessException;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SMSUtil {
    public static void main(String[] args) {
        SMSUtil smsUtil = new SMSUtil();
//        String content = "【雏蜂金服】验证码：123456，您正在申请注册雏蜂金服商家账号，请勿将其提供给他人。验证码1分钟之内有效。";
//        smsUtil.sendSMSToMobile("13826587990", content);
        // PropertisUtil.setPropsValue("alarm_time",DateUtil.formatDate("yyyy-MM-dd"));
        /*String code = "888888";
        int validTime = 3;
        String paramJson="{\"code\":\""+code+"\",\"time\":\""+validTime+"\"}";
        smsUtil.sendMsgALDY(SmsConstants.ALDY_SMS_TEMPLATE_REGISTER, "", paramJson);*/
        smsUtil.sendMsgUMS_LC("", "验证码:888888,您正在申请注册蓝创商服商家账号,请勿将其提供给他人。验证码5分钟之内有效。");
    }

    private static SMSUtil instance = new SMSUtil();

    private static final Logger log = LoggerFactory.getLogger(SMSUtil.class);

    private SMSUtil() {
        // TODO Auto-generated constructor stub
    }

    public boolean sendSMSToMobile(String phoneNumber, String content) {
        String pwd = Md5Utils.getMD5(SmsConstants.SMS_URL_PWD);
        try {
            content = URLEncoder.encode(content, SmsConstants.SMS_ENCODE);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String url = MessageFormat.format(SmsConstants.SMS_URL, SmsConstants.SMS_URL_SN, pwd, phoneNumber, content, Constants.SMS_EXT);
        List<String> readline = null;
        try {
            URLConnection webUrlRequest = webUrlRequest(url);
            log.info("================开始发送短信，url={}", url);
            readline = readLine(webUrlRequest.getInputStream());
            log.info("================短信服务器返回:{}", readline);
        } catch (Exception e) {
            // handle_exception("sendSMSToMobile Exception:" + e.getMessage());
            log.error("================短信发送异常", e);
            return false;
        }
        if (readline != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送阿里大于验证码
     *
     * @param templateCode 短信模板编号
     * @param mobiles      接收者手机号码
     * @param paramJson    参数String串，如： {\"code\":\"1234\",\"time\":\"3\"}
     *                     此处 code和time 是短信模板的参数
     * @author
     * @date 2017年3月22日 上午11:09:34
     */
    public boolean sendMsgALDY(String templateCode, String mobiles, String paramJson) {
        TaobaoClient client = new DefaultTaobaoClient(SmsConstants.ALDY_SMS_URL, SmsConstants.ALDY_SMS_KEY, SmsConstants.ALDY_SMS_SECRET);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("");
        req.setSmsType("normal");
        req.setSmsFreeSignName("雏蜂金服");
        req.setSmsParamString(paramJson);
        req.setRecNum(mobiles);
        req.setSmsTemplateCode(templateCode);
        AlibabaAliqinFcSmsNumSendResponse rsp;
        try {
            rsp = client.execute(req);
             if (rsp.getResult().getSuccess()) {
                log.info("短信发送成功{}", mobiles);
                return true;
            } else {
                log.error("短信发送失败:errCode={}, msg={}",rsp.getResult().getErrCode(), rsp.getResult().getMsg());
                return false;
            }
        } catch (ApiException e) {
            log.error("发送阿里大于短信失败", e);
            return false;
        }
    }

    public boolean sendMsgUMS(String mobiles, String content) {
        String info;
        try {
            HttpClient httpclient = new HttpClient();
            PostMethod post = new PostMethod("http://gd.ums86.com:8899/sms/Api/Send.do");//
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
            post.addParameter("SpCode", "237046");
            post.addParameter("LoginName", "admin3");
            post.addParameter("Password", "DGyinlian@123");
            //模板信息   现有模板：1、验证码{xxxxxxxx}您正在使用{xxxx}产品{x}需要进行校验请勿向任何人提供您收到的短信验证码 2、你有一项编号为{xxxxxxxxxxx}的事务需要处理{x}
            post.addParameter("MessageContent", content);
            //用户手机号
            post.addParameter("UserNumber", mobiles);
            post.addParameter("SerialNumber", "");
            post.addParameter("ScheduleTime", "");
            post.addParameter("ExtendAccessNum", "");
            post.addParameter("f", "1");
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "gbk");
            Map<String, String> map = StringUtil.splitStringToMap(info);
            if ("0".equals(map.get("result"))) {
                log.info("发送一信通短信成功{}", info);
                return true;
            } else {
                log.error("发送一信通短信失败{}", info);
                throw new BusinessException(map.get("description"));
            }
        } catch (Exception e) {
            log.error("发送一信通短信异常{}", e);
            return false;
        }
    }

    /**
     * 蓝创科技一信通短信通道
     *
     * @param mobiles
     * @param content
     * @return
     * @author zouwenjun
     * @date 2017年7月6日 下午1:53:47
     */
    public boolean sendMsgUMS_LC(String mobiles, String content) {
        String info;
        try {
            HttpClient httpclient = new HttpClient();
            PostMethod post = new PostMethod("http://gd.ums86.com:8899/sms/Api/Send.do");//
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
            post.addParameter("SpCode", "242146");
            post.addParameter("LoginName", "admin0");
            post.addParameter("Password", "esoonpay321");
            post.addParameter("MessageContent", content);
            //用户手机号
            post.addParameter("UserNumber", mobiles);
            post.addParameter("SerialNumber", "");
            post.addParameter("ScheduleTime", "");
            post.addParameter("ExtendAccessNum", "");
            post.addParameter("f", "1");
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "gbk");
            Map<String, String> map = StringUtil.splitStringToMap(info);
            if ("0".equals(map.get("result"))) {
                log.info("蓝创发送一信通短信成功{}", info);
                return true;
            } else {
                log.error("蓝创发送一信通短信失败{}", info);
                throw new BusinessException(map.get("description"));
            }
        } catch (Exception e) {
            log.error("蓝创发送一信通短信异常{}", e);
            return false;
        }
    }

    public URLConnection webUrlRequest(String requestUrl) throws IOException {
        return new URL(requestUrl).openConnection();
    }

    public List<String> readLine(InputStream inputStream) throws IOException {
        List<String> list = new ArrayList<String>();
        BufferedReader bufferReader = null;
        try {
            bufferReader = new BufferedReader(new InputStreamReader(
                    inputStream, SmsConstants.SMS_ENCODE));

            String readline;
            while ((readline = bufferReader.readLine()) != null) {
                list.add(readline);
            }
        } finally {
            bufferReader.close();
        }
        return list;
    }

    public static SMSUtil getInstance() {
        return instance;
    }


}
